package ch.vd.horario.vaadin.util;

import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

public class BusStopHtmlPageParser implements Serializable {

	private static final long serialVersionUID = -4732705543173788471L;

	public static List<String> parse(int lineNb, String direction, String busStop) throws MalformedURLException,
			IOException {
		List<String> result = new LinkedList<String>();

		String sourceUrlString = "http://www.t-l.ch/htr.php?ligne=" + lineNb + "&sens=" + direction + "&arret="
				+ busStop;

		Source source = new Source(new URL(sourceUrlString));
		// have to create a new Source object after changing tag type registrations otherwise cache might contain tags found with previous configuration.
		source = new Source(source);

		List<Element> allTables = source.getAllElements(HTMLElementName.TABLE);
		for (Element table : allTables) {
			List<Element> rows = table.getAllElements(HTMLElementName.TD);
			for (Element row : rows) {
				result.add(row.getRenderer().toString().replace('*', ' ').trim());
			}

		}

		return result;
	}

}
